document.addEventListener('DOMContentLoaded', function() {
    const registerForm = document.getElementById('registerForm');
    const roleRadios = document.querySelectorAll('input[name="role"]');
    const addressContainer = document.getElementById('addressContainer');
    
    // 监听角色选择
    roleRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.value === '学生') {
                addressContainer.style.display = 'block';
            } else {
                addressContainer.style.display = 'none';
            }
        });
    });
    
    registerForm.addEventListener('submit', function(event) {
        event.preventDefault();
        
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        const contact = document.getElementById('contact').value;
        const role = document.querySelector('input[name="role"]:checked').value;
        let address = '';
        
        if (role === '学生') {
            address = document.getElementById('address').value;
            if (!address) {
                alert('请输入地址');
                return;
            }
        }
        
        // 验证密码是否一致
        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            return;
        }
        
        // 验证用户名和密码是否为空
        if (!username || !password) {
            alert('用户名和密码不能为空');
            return;
        }
        
        // 验证联系方式是否为空
        if (!contact) {
            alert('请输入联系方式');
            return;
        }
        
        // 构建注册数据
        const registerData = {
            username: username,
            password: password,
            name: contact,  // 根据前端表单结构，这里的contact实际上是姓名
            phone: contact, // 根据前端表单结构，这里的contact实际上也是手机号
            role: role === '学生' ? 'student' : 'delivery_person',
            address: address
        };
        
        // 发送注册请求到后端API
        fetch('http://localhost:5000/api/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(registerData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alert('注册成功，请登录');
                window.location.href = 'login.html';
            } else {
                alert('注册失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('注册请求失败：', error);
            alert('注册请求失败，请稍后重试');
        });
    });
});